package com.andnnl.filter;

import com.andnnl.fileanalysis.AnalysisListenerRow;
import com.andnnl.fileanalysis.AnalysisParam;
import com.andnnl.fileanalysis.FileAnalysisManage;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.Normalizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ContentValidator {
    // 特殊拦截号码前缀列表
    private static final String[] BLOCKED_PREFIXES = {
            "95", "96", "123", "100", "110", "119", "120", "121", "122", "12122", "65"
    };

    private static final Pattern regexIp = Pattern.compile("((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE);
    private static final Pattern regex = Pattern.compile("((http://|https://){0,1}([\\w\\-~]+\\.)+([a-z]){2,6})(/.*)?", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE);

    public static boolean processContent(String input) throws IllegalArgumentException {
        // 1. 替换所有连字符
        String processed = input.replaceAll("[- :\r\n]", "");
        // 所有数字全角转为半角
        processed = Normalizer.normalize(processed, Normalizer.Form.NFKC);

        // 2. 校验数字组规则
        if (!validateDigitGroups(processed)) {
            return false;
        }

        // 4. 拦截IP地址
        if (regexIp.matcher(processed).find()) {
            System.out.println("禁止使用IP地址:" + processed);
            return false;
        }

        // 5. 拦截URL
        if (regex.matcher(processed).find()) {
            System.out.println("禁止使用URL:" + processed);
            return false;
        }
        return true;
    }

    private static boolean validateDigitGroups(String str) {
        // 匹配所有连续数字组
        Pattern pattern = Pattern.compile("(?<!\\d)\\d+(?!\\d)");
        Matcher m = pattern.matcher(str);


        while (m.find()) {
            final String s = m.group();
            if (s.length() > 6) {
                System.out.println("数字长度不能超过6位:" + s);
                return false;
            }
            // 3. 拦截特殊号码
            if (!checkBlockedNumbers(s)) {
                System.out.println("禁止使用特殊号码:" + s);
                return false;
            }
        }
        return true;
    }

    private static boolean checkBlockedNumbers(String str) {
        for (String prefix : BLOCKED_PREFIXES) {
            if (str.startsWith(prefix)) {
                System.out.println("禁止使用特殊号码: " + prefix + "xxx");
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        try {
            System.out.println("sssssssssssssss");
            System.out.println(processContent("【芒果tv】843714（随机验证码），有效期10分钟。如非本１２３４３４５６７８９０人使用，敬请忽略本信息。"));  // 正常
//            System.out.println("-----------------------------------------------------------------------------------------");
//            System.out.println(processContent("【深圳农商银行】您的信用卡本期账单为￥0元，最低还款额0元，到期还款日为20250710。手机查账单，还能办分期！我行全新推出升级版账单啦，账单详情请点击 t.961200.net/m/5n4D4f 。"));  // 正常
//            System.out.println("-----------------------------------------------------------------------------------------");
//            System.out.println(processContent("【希望学】孙洪林老师提醒，您的9月上二年级数学升学衔接提升课在2025-06-30 19:00有一场直播课。请按时参加，如不能参加，请联系希望学辅导老师请假哦！"));  // 正常
//            System.out.println("-----------------------------------------------------------------------------------------");
//            System.out.println(processContent("【中银国际】双重认证验证码︰184227--905815 (有效期至 18:42:27)"));  // 正常
//            System.out.println("-----------------------------------------------------------------------------------------");
//            System.out.println(processContent("【深圳法院】
            //按行读取data.csv
//            String line;
//            BufferedReader br = new BufferedReader(new FileReader("data.csv"));
//            while ((line = br.readLine()) != null) {
//                System.out.println(processContent(line));
//                System.out.println("-----------------------------------------------------------------------------------------");
//            }

            AnalysisParam param = AnalysisParam.build()
                    .setBatchSize(1000)//读到一批后调用一次invokeBatch
                    .setDelHeadRows(1)//删除头部行数，空行不算
//                .setExt("txt")//指定解析的文件格式
//                .setCharset("UTF-8")//指定解析的文件编码
//                .setCharset("GBK")//指定解析的文件编码
//                .setSplitLimit(3)//txt分割2列
                    .setMaxRow(0);//限制读取行数,0:不限制
//        CountListener countlistener = new CountListener();
//        FileAnalysisManage.analysis(file, countlistener, param);
//        logger.info("listener.count:" + countlistener.getCount());
            FileWriter writer = new FileWriter("C:\\workspace\\testjava8\\src\\main\\resources\\data_rs_3.txt");
            File file = new File("C:\\workspace\\testjava8\\src\\main\\resources\\data.csv");
            AnalysisListenerRow listener = row -> {
//                System.out.println(row);
                final String str = row.get(0);
                final boolean rs = processContent(str);
//                System.out.println(rs);
                if (rs) {
                    System.out.println(str);
                    try {
                        writer.append(str);
                        writer.append("\r\n");
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println("-----------------------------------------------------------------------------------------");

            };
            FileAnalysisManage.analysis(file, listener, param);
            writer.flush();
        } catch (Exception e) {
        }
    }
}